//
//  stack.cpp
//  Cpp_Demo
//
//  Created by Robin Guo on 2017/9/24.
//  Copyright © 2017年 Robin Guo. All rights reserved.
//

#include "stack.hpp"

template<class T>
stack<T>::stack() {
    _top = new node<T>;
    _top->next = NULL;
    _size = 0;
}

// [node0] <- [node1] <- [node2] <- _top;
template<class T>
stack<T>::~stack() {
    node<T> *cur;
    cur = _top;
    while (cur) {
        _top = cur->next;
        delete cur;
        cur = _top;
    }
}

// 单链表 第一个节点前附设一个节点，叫头节点。头结点可以存储一些附加信息，如链表长度、当前遍历位置等附加信息；
// 链表首尾到底要不要保存数据
// 入栈
template<class T>
void stack<T>::push(T element) {
    node<T> *n;
    n = new node<T>;
    _top->data = element; // 数据入栈

    // 指针向上指 [node] <- [top]
    if (!n) {
        abort();
    }
    n->next = _top;
    _top = n;
    _size++;
}

template<class T>
T stack<T>::pop() {
    
    node<T> *_del;
    if (_size > 0) {
        _del = _top->next;
        _top->next = _del->next;
        T rv = _del->data;
        delete _del;
        _size--;
        return rv;
    }
    
    return NULL;
}

template<class T>
T stack<T>::top() {
    return _top->next->data;
}

template<class T>
int stack<T>::size() {
    return _size;
}

template<class T>
bool stack<T>::isEmpty() {
    return _size==0?true:false;
}







